<template>
  <!-- 系统管理 -->
  <div class="app-container">
    <div class="mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form ref="filterFormRef" :inline="true" :model="filterForm">
          <el-form-item label="项目名称:" prop="projectName">
            <el-input
              v-model.trim="filterForm.projectName"
              class="filter-item limit"
              style="width: 200px;margin-right:10px"
              maxlength="30"
              clearable
              placeholder="请输入公司名称"
              @keyup.enter.native="$_handleFilter"
            />
          </el-form-item>
          <el-form-item label="公司名称:" prop="companiesName">
            <el-input
              v-model.trim="filterForm.companiesName"
              class="filter-item limit"
              style="width: 200px;margin-right:10px"
              maxlength="30"
              clearable
              placeholder="请输入公司名称"
              @keyup.enter.native="$_handleFilter"
            />
          </el-form-item>
          <el-form-item label="项目状态:" prop="stateType">
            <el-select v-model.trim="filterForm.stateType" placeholder="请选择" :clearable="true">
              <el-option
                v-for="dict in statesList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="签约时间:" prop="name">
            <el-date-picker
              v-model="filterForm.times"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              align="right">
            </el-date-picker>
          </el-form-item>
          <el-button type="primary" @click="$_handleFilter">查询</el-button>
          <el-button @click="$_handleReset">重置</el-button>
        </el-form>

      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['PROJECTMANAGEMENT_ADD_BUTTON']"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-dropdown style="margin-left: 10px;margin-right: 10px;">
            <el-button
              v-permission="['PROJECTMANAGEMENT_EXPORT_BUTTON']"
              icon="el-icon-folder-remove"
              type="primary"
              size="medium"
            >导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown" style="width:108px;text-align:center">
              <el-dropdown-item
                @click.native="handleExport('export', 1)"
              >央企导出</el-dropdown-item>
              <el-dropdown-item
                @click.native="handleExport('export')"
              >非央企导出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="MX_listLoading"
          :data="MX_list"
          border
          highlight-current-row
          :row-key="$_getRowKey"
          style="width: 100%;text-align:center"
          :header-cell-style="MX_headerCellStyle"
        >
          <template slot="empty">
            <p>暂无数据!</p>
          </template>
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            align="center"
            :index="$_tableIndex"
          />
          <el-table-column
            v-for="item in columns"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :min-width="item.minWidth"
            :formatter="item.formatter"
            align="center"
          />
          <el-table-column
            :key="Math.random()"
            fixed="right"
            label="操作"
            width="220px"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="tBtn"
                @click="goto(`ProjectManagementForm?id=${scope.row[idKeyName]}&detail=1`)"
              >详情</el-button>
              <el-button
                v-permission="['PROJECTMANAGEMENT_UPDATE_BUTTON']"
                size="mini"
                class="tBtn"
                @click="goto(`ProjectManagementForm?id=${scope.row[idKeyName]}`)"
              >修改</el-button>
              <el-button
                v-permission="['PROJECTMANAGEMENT_DEL_BUTTON']"
                size="mini"
                type="danger"
                class="tBtn"
                @click="handleDelete(scope.row[idKeyName])"
              >删除</el-button>
              <el-button
                v-if="scope.row.auditType !== 1"
                v-permission="['PROJECTMANAGEMENT_CHANGE_BUTTON']"
                size="mini"
                class="tBtn"
                type="primary"
                @click="handleChangeState(scope.row)"
              >状态变更</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="MX_total > 0"
          :total="MX_total"
          :page.sync="MX_pageNav.pageNo"
          :limit.sync="MX_pageNav.pageSize"
          @pagination="getList"
        />
      </div>
      <DialogForm ref="dialogForm" labelWidth="140px" :formDesignList="formDesignList">
        <div slot="other" v-if="!!historyList.length">
          <div class="historyListBar">
            <i class="el-icon-caret-right"></i>
            <div class="list">
              <div class="item" v-for="(v, k) in historyList" :key="k">
                <div class="tag">{{getstatesLabel(v.stateType)}}</div>
                <p>{{!!v.createTime ? v.createTime.split(' ')[0] : ''}}</p>
              </div>
            </div>
          </div>
        </div>
      </DialogForm>
      <dtDialog
        :title="`${!!isYQ ? '' : '非'}央企导入`"
        class="get-page-form-import-dialog"
        :visible.sync="MX_fileUploadVisible"
        width="620px"
        :is-loading="MX_uploadLoading"
        @closeDialog="MX_fileUploadVisible = false"
        @comfirmBtn="$_importDataSave(!!isYQ ? importApiYQ : importApi)"
      >
        <el-form slot="content">
          <div class="">
            <dt-importFile ref="dtImportFileRef" :down-load-template="!!isYQ ? handleImportTemplateYQ : handleImportTemplate" :type="`${!!isYQ ? '央企' : ''}${fileName}`" />
          </div>
        </el-form>
      </dtDialog>
    </div>
  </div>
</template>
<script>
import trackApi from '@/api/investment/track'
import DialogForm from '@/views/investment/components/DialogForm'
import commonList from "@/utils/mixins/investment/commonList";
import intservApi from "@/api/investment/intserv";
import dataCaptureApi from "@/api/investment/dataCapture";
import systemApi from "@/api/investment/system";
const statesList = [
  {value: 1,label:'未签约'},
  {value: 2,label:'已签约'},
  {value: 3,label:'已落实'},
  {value: 4,label:'已投产'},
  {value: 5,label:'项目异常'}
]
export default {
  dicts: ['QYLX'],
  name: 'ProjectManagement',
  components: {
    DialogForm
  },
  mixins: [commonList],
  data() {
    const _this = this
    return {
      filterForm: {
        companiesName: '',
        projectName: '',
        stateType: '',
        times: ''
      },
      fileName: '项目管理数据导入',
      handleImportTemplateYQ: trackApi.downloadXM_MANAGEYQ,
      importApiYQ: trackApi.importXM_MANAGEYQ,
      handleImportTemplate: trackApi.downloadXM_MANAGE,
      importApi: trackApi.importXM_MANAGE,
      isYQ: '',
      statesList,
      // 列信息
      columns: [
        { prop: 'dedicatedName', label: `专班名称`, minWidth: '140px', formatter: (row) => {
            let item = _this.zbList.filter(v => v.value === row.dedicatedId)
            return item.length ? item[0].label : ''
          } },
        { prop: 'companiesName', label: `公司名称(投资方名称)`, minWidth: '140px' },
        { prop: 'companiesCode', label: `企业类型`, width: '140px', formatter: (row) => {
            return _this.dict.label.QYLX[row.companiesCode] || ''
          } },
        { prop: 'contactsName', label: `联系人`, width: '90px'  },
        { prop: 'contactsPhone', label: `联系电话`, minWidth: '140px' },
        { prop: 'projectName', label: `项目名称`, minWidth: '140px' },
        { prop: 'investmentPlan', label: `计划总投资（亿元）`, width: '140px' },
        { prop: 'constructionYearlyOutput', label: `建后年产`, width: '140px' },
        { prop: 'constructionTaxation', label: `建后税收`, width: '140px' },
        { prop: 'constructionJobs', label: `建后可提供就业岗位`, width: '140px' },
        { prop: 'agencyTime', label: `拟签约时间`, width: '180px' },
        { prop: 'fillTime', label: `首次填报时间`, width: '180px' },
        { prop: 'stateType', label: `项目状态`, width: '120px', formatter: function(row) {
            let info = _this.statesList.filter(v => v.value === row.stateType)
            return !!info.length ? info[0].label : ''
          } },
      ],
      formDesignList: [
        { type: 'select', prop: 'stateType', label: `变更状态`, dictOptions: statesList, rules: [{ required: true, message: '请选择变更状态', trigger: 'change' }] },
        { type: 'datetime', prop: 'stateTime', label: `变更时间`, format: 'yyyy-MM-dd HH:mm:ss', valueFormat: 'yyyy-MM-dd HH:mm:ss', rules: [{ required: true, message: '请选择变更时间', trigger: 'blur' }] },
      ],
      idKeyName: 'manageId',
      historyList: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      userZBInfo: {},
      zbList: [],
    }
  },
  watch: {
    'filterForm.times'(val){
      this.$set(this.filterForm, 'searchBeginTime', !!val ? val[0] : '')
      this.$set(this.filterForm, 'searchEndTime', !!val ? val[1] : '')
    }
  },
  created() {
    this.getList()
    this.getUserZBInfo()
    this.getZBList()
  },
  methods: {
    getUserZBInfo(){
      dataCaptureApi.getUserOfZB().then(res => {
        this.userZBInfo = res.data
      })
    },
    getZBList(){
      systemApi.getZBList({pageSize: -1}).then(res => {
        let list = res.data.rows || [];
        this.zbList = list.map(v => {
          v.value = v.id
          v.label = v.groupName
          return v
        })
      })
    },
    // 获取页面列表
    getList() {
      let filterForm = JSON.parse(JSON.stringify(this.filterForm))
      delete filterForm.times
      this.$_getList(trackApi.getXM_MANAGEList,{
        ...filterForm,
        ...this.MX_pageNav
      })
    },
    handleAdd(){
      if(!this.userZBInfo.specializedId) {
        this.$dtMessage({type: 'error', message: '当前用户不为专班成员，不可新增！'})
        return
      }
      this.goto(`ProjectManagementForm`)
    },
    // 删除按钮
    handleDelete(id) {
      this.$_handleDelete(intservApi.delZS_MANAGEItem, [id], `${this.idKeyName}s`)
    },
    //导入
    handleImport(isYQ){
      if(!this.userZBInfo.specializedId) {
        this.$dtMessage({type: 'error', message: '当前用户不为专班成员，不可导入！'})
        return
      }
      this.isYQ = isYQ
      this.$_handleImport()
    },
    /** 导出/下载按钮操作 */
    handleExport(type = 'export', isYQ) {
      if (type === 'export'){
        this.$_handleDownload(trackApi[`exportXM_MANAGE${!!isYQ ? 'YQ' : ''}`], `${!!isYQ ? '央企' : ''}项目管理列表`, this.filterForm, '导出');
      }else{
        this.$_handleDownload(this[`handleImportTemplate${!!isYQ ? 'YQ' : ''}`], `${!!isYQ ? '央企' : ''}${this.fileName}模板`);
      }
    },
    //状态变更
    handleChangeState(data){
      this.historyList = []
      this.getHistoryList(data[this.idKeyName])
      this.$refs.dialogForm.open('changeState', intservApi.updateZS_MANAGEItem, { [this.idKeyName]: data[this.idKeyName] })
    },
    getHistoryList(id){
      trackApi.gethistoryXM_MANAGEState({
        [this.idKeyName]: id
      }).then(res => {
        this.historyList = res.data || []
      })
    },
    getstatesLabel(code){
      let info = this.statesList.filter(v => v.value === code)
      return !!info.length ? info[0].label : ''
    },
    goto(url){
      this.$router.push(`/investment/track/${url}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.tBtn{
  margin-top: 3px;
  margin-bottom: 3px;
}
.historyListBar{
  position: relative;
  padding-top: 20px;
  &:before{
    position: absolute;
    content: '';
    width: calc(100% - 18px);
    height: 2px;
    left: 0;
    top: calc(50% + 9px);
    background-color: #B6DBFF;
    z-index: 2;
  }
  .el-icon-caret-right{
    position: absolute;
    right: 0;
    color: #B6DBFF;
    font-size: 30px;
    top: calc(50% - 5px);
    z-index: 1;
  }
  .list{
    width: 100%;
    overflow-x: auto;
    position: relative;
    z-index: 3;
    display: flex;
    justify-content: center;
    .item{
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      font-size: 16px;
      position: relative;
      text-align: center;
      color: #333;
      font-weight: 600;
      padding: 0 10px;
      flex-shrink: 0;
      flex-grow: 0;
      &:before{
        position: absolute;
        content: '';
        width: 14px;
        height: 14px;
        background-color: #1289FF;
        border: 2px solid #B6DBFF;
        border-radius: 50%;
        top: calc(50% - 7px);
      }
      &:last-of-type{
        .tag{
          background-color: #1289FF;
          color: #fff;
        }
      }
      .tag{
        background: #F1F2F5;
        border-radius: 4px;
        padding: 4px 8px;
        font-size: 14px;
      }
      p{
        width: 100%;
        margin-top: 30px;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
